package me.yiyou.meihua.ui.page.memory

import android.content.Context
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.kongzue.dialogx.dialogs.PopTip
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.yiyou.meihua.MyApplication
import me.yiyou.meihua.data.Gua
import me.yiyou.meihua.data.GuaList
import java.io.IOException

class MemoryViewModel : ViewModel() {
    // 状态管理
    val guaList = mutableStateOf<List<Gua>?>(null)
    val isLoading = mutableStateOf(false)
    val error = mutableStateOf<String?>(null)

    // 题目下标
    val currentIndex = mutableStateOf(0)

    // 搜索卦宫
    private val _searchInput = mutableStateOf("")
    val searchInput: State<String> = _searchInput

    // 根据上下卦搜索卦宫
    private val _searchShang = mutableStateOf("")
    val searchShang: State<String> = _searchShang
    private val _searchXia = mutableStateOf("")
    val searchXia: State<String> = _searchXia

    private val _searchResult = mutableStateOf("")
    val searchResult: State<String> = _searchResult

    fun onSearchInputChanged(input: String) {
        _searchInput.value = input
    }

    fun onSearchShangInputChanged(input: String) {
        _searchShang.value = input
    }

    fun onSearchXiaInputChanged(input: String) {
        _searchXia.value = input
    }

    /**
     * 加载卦象json数据
     */
    fun loadGuaData() {
        viewModelScope.launch(Dispatchers.IO) {
            isLoading.value = true
            try {
                val data = parseGuaFromAssets(MyApplication.appContext, "gua.json")
                guaList.value = data?.gua ?: emptyList()
            } catch (e: Exception) {
                error.value = when (e) {
                    is IOException -> "文件读取失败"
                    is JsonSyntaxException -> "数据解析错误"
                    else -> "未知错误: ${e.message}"
                }
            } finally {
                isLoading.value = false
            }
        }
    }

    /**
     * 读取并解析 JSON 的工具函数
     */
    private fun parseGuaFromAssets(context: Context, fileName: String): GuaList? {
        return try {
            val jsonString = context.assets.open(fileName)
                .bufferedReader()
                .use { it.readText() }

            Gson().fromJson(jsonString, GuaList::class.java)
        } catch (e: IOException) {
            e.printStackTrace()
            null
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 根据名字查找卦象
     */
    fun findGuaByName(name: String): Gua? {
        return guaList.value?.firstOrNull { it.ming == name }
    }

    /**
     * 根据卦名寻找卦宫
     */
    fun findGuaGongByName() {
        var result: Gua? = null
        if (_searchInput.value.isNotEmpty() && _searchShang.value.isEmpty() && _searchXia.value.isEmpty()) {
            result = guaList.value?.firstOrNull { it.ming == searchInput.value }
        } else if (_searchInput.value.isEmpty() && _searchShang.value.isNotEmpty() && _searchXia.value.isNotEmpty()) {
            result =
                guaList.value?.firstOrNull { it.shang == _searchShang.value && it.xia == _searchXia.value }
        } else {
            PopTip.show("输入有误,请重新输入!")
        }
        if (result != null) {
            _searchResult.value = result.gong
        } else {
            _searchResult.value = "输入有误!请重新输入!"
        }
    }

    /**
     * 根据卦名寻找卦宫
     */
    fun findPartGuaByName(shang: String, xia: String): String {
        return guaList.value?.firstOrNull { it.shang == shang && it.xia == xia }?.gong.toString()
    }

    /**
     * 切换到下一个卦象
     */
    fun onNextQuestion() {
        guaList.value?.let { list ->
            currentIndex.value = (currentIndex.value + 1) % list.size
        }
    }

    /**
     * 切换到上一个卦象
     */
    fun onPreviousQuestion() {
        guaList.value?.let { list ->
            currentIndex.value = (currentIndex.value - 1) % list.size
        }
    }

    /**
     * 当前题目的文本
     */
    val currentPositionText: String
        get() = guaList.value?.let {
            "${currentIndex.value + 1}/${it.size}"
        } ?: "0/0"
}